import { query } from '@angular/animations';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { apiConf } from '@conf/api.conf';
import {
  SFCascaderWidgetSchema,
  SFCheckboxWidgetSchema,
  SFComponent,
  SFDateWidgetSchema,
  SFSchema,
  SFStringWidgetSchema,
  SFTextareaWidgetSchema,
  SFUISchema,
  SFUploadWidgetSchema
} from '@delon/form';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { of } from 'rxjs';
import { SystemService } from '../../../services/system.service';

const IMAGECONFIG = {
  previewFile: (file: NzUploadFile) => of(file.url),
  action: apiConf.waterFileUpload,
  fileType: 'image/png,image/jpeg,image/jpg,image/gif',
  fileSize: 5120,
  limit: 1,
  limitFileCount: 1,
  resReName: 'data.fullFileWatermarkPath',
  urlReName: 'data.fullFileWatermarkPath',
  widget: 'upload',
  name: 'multipartFile',
  multiple: false,
  listType: 'picture-card'
} as SFUploadWidgetSchema;

const DATECONFIG = {
  grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
  widget: 'date',
  format: 'yyyy-MM-dd',
  placeholder: '请选择'
};

@Component({
  selector: 'app-network-freight-new-component',
  templateUrl: './new.component.html',
  styleUrls: ['./new.component.less']
})
export class NetworkFreightNewComponent implements OnInit {
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  @ViewChild('sf1', { static: false })
  sf1!: SFComponent;
  sf1FormData: any = {
    legalPersonIdentityVO: {
      certificatePhotoFrontWatermark: '',
      certificatePhotoBackWatermark: '',
      roadTransportPhotoWatermark: ''
    }
  };
  subText = '确认新增';
  TabText = '新增网络货运人';
  sf2FormData: any = {};
  schema: SFSchema = this.initOthersSF();
  schema1: SFSchema = this.initBasicInfoSF();
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 180,
      grid: { span: 24 }
    },
    $title1: {
      spanLabelFixed: 0
    },
    $title99: {
      spanLabelFixed: 0
    },
    $title2: {
      spanLabelFixed: 0
    },
    $registrationCapital: {
      spanLabelFixed: 180,
      grid: { xxl: 13, xl: 18, lg: 22, md: 22 }
    },
    $unit: {
      grid: { xxl: 6, xl: 6, lg: 2, md: 2 }
    },
    $isLoingDate: {
      spanLabelFixed: 100,
      grid: { xxl: 6, xl: 6, lg: 4, md: 6 }
    },
  };

  constructor(private router: Router, public service: SystemService, private route: ActivatedRoute) {}
  ngOnInit() {
    if (this.route.snapshot.params.id !== 'undefined') {
      this.dataListInit(this.route.snapshot.params.id);
      this.subText = '确认编辑';
      this.TabText = '编辑网络货运人';
    }
  }
  dataListInit(id: any) {
    this.service.request(this.service.$api_get_networkTransporter_getDetail, { id: id }).subscribe(res => {
      console.log(res);
      this.sf2FormData = res;
      this.sf1FormData = res.enterpriseInfoVO;
      this.sf1FormData.legalPersonIdentityVO.roadTransportLicenceNo = res.roadTransportLicenceNo;
      this.sf1FormData.legalPersonIdentityVO.roadTransportAddress = res.roadTransportAddress;
      this.sf1FormData.legalPersonIdentityVO.roadTransportStartTime = res.roadTransportStartTime;
      this.sf1FormData.legalPersonIdentityVO.roadTransportEndTime = res.roadTransportEndTime;
      this.sf1FormData.isLoingDate = this.sf1FormData.operatingEndTime !== null ? false : true;
      this.sf1FormData.licensePhotoWatermark = [
        {
          uid: -1,
          name: 'LOGO',
          status: 'done',
          url: this.sf1FormData.licensePhotoWatermark,
          response: this.sf1FormData.licensePhotoWatermark
        }
      ];
      console.log(this.sf1FormData);
      // 营业执照法人信息

      this.sf1FormData.legalPersonIdentityVO.certificatePhotoFrontWatermark = [
        {
          uid: -1,
          name: 'LOGO',
          status: 'done',
          url: res.enterpriseInfoVO.legalPersonIdentityVO.certificatePhotoFrontWatermark,
          response: res.enterpriseInfoVO.legalPersonIdentityVO.certificatePhotoFrontWatermark
        }
      ];
      this.sf1FormData.legalPersonIdentityVO.certificatePhotoBackWatermark = [
        {
          uid: -1,
          name: 'LOGO',
          status: 'done',
          url: this.sf1FormData.legalPersonIdentityVO.certificatePhotoBackWatermark,
          response: this.sf1FormData.legalPersonIdentityVO.certificatePhotoBackWatermark
        }
      ];
      this.sf1FormData.legalPersonIdentityVO.roadTransportPhotoWatermark = [
        {
          uid: -1,
          name: 'LOGO',
          status: 'done',
          url: res.roadTransportPhotoWatermark,
          response: res.roadTransportPhotoWatermark
        }
      ];
      const province = this.sf1FormData.fullRegionVO.provinceCode;
      const city = this.sf1FormData.fullRegionVO.cityCode;
      const area = this.sf1FormData.fullRegionVO.areaCode;
      this.sf1FormData.enterpriseAddressCode = [parseInt(province), parseInt(city), parseInt(area)];
      this.getRegionToThree();
    });
  }
  getRegionToThree() {
    // 获取一、二、三级地区详情
    this.service.http.post(this.service.$api_getRegionToThree).subscribe(res => {
      if (this.sf1) {
        this.sf1.getProperty('/enterpriseAddressCode')!.schema.enum = res.data;
        this.sf1?.getProperty('/enterpriseAddressCode')?.widget.reset(res.data);
      }
    });
  }
  submitForm() {
    if (!this.sf1.valid || !this.sf.valid) {
      this.sf.validator({ emitError: true });
      this.sf1.validator({ emitError: true });
      this.service.msgSrv.warning('请填写必填项！');
      return;
    }
    const enterpriseRegistrationTime = new Date(this.sf1.value.enterpriseRegistrationTime);
    const operatingStartTime = new Date(this.sf1.value.operatingStartTime);
    if (enterpriseRegistrationTime.getTime() > operatingStartTime.getTime()) {
      this.service.msgSrv.warning('营业期限不能小于成立日期');
      return;
    }
    if (this.sf1.value.operatingEndTime) {
      const operatingEndTime = new Date(this.sf1.value.operatingEndTime);
      if (operatingStartTime.getTime() > operatingEndTime.getTime()) {
        this.service.msgSrv.warning('营业期限不能小于期限开始日期');
        return;
      }
    }
    if (this.sf1.value.isLoingDate) {
      this.sf1.value.operatingEndTime = '';
    }
    const sfVlaue = this.sf1.value;
    const params: any = {};
    Object.assign(params, {
      ...this.sf?.value,
      enterpriseInfoDTO: {
        ...this.sf1.value,
        legalPersonIdentityDTO: this.sf1.value.legalPersonIdentityVO,

      },
      roadTransportAddress: this.sf1.value.legalPersonIdentityVO.roadTransportAddress, //道路运输证地址
      roadTransportEndTime: this.sf1.value.legalPersonIdentityVO.roadTransportEndTime, //道路运输许可证有效结束时间
      roadTransportStartTime: this.sf1.value.legalPersonIdentityVO.roadTransportStartTime, //道路运输许可证有效开始时间
      roadTransportPhotoWatermark: this.sf1.value.legalPersonIdentityVO.roadTransportPhotoWatermark, //带水印道路运输照片
      roadTransportPhoto: this.sf1.value.legalPersonIdentityVO.roadTransportPhoto, //经营许可证号
      roadTransportLicenceNo: this.sf1.value.legalPersonIdentityVO.roadTransportLicenceNo, //道路运输照片
    });
    delete params.enterpriseInfoDTO.legalPersonIdentityVO;
    params.enterpriseInfoDTO.enterpriseAddressCode = this.sf1.value?.enterpriseAddressCode?.[2];
    if (this.route.snapshot.params.id !== 'undefined') {
      params.id = this.route.snapshot.params.id;
    }
    this.service.request(this.service.$api_networkTransporter_save, params).subscribe(res => {
      if (res) {
        if (this.route.snapshot.params.id !== 'undefined') {
          this.service.msgSrv.success('修改成功');
        } else {
          this.service.msgSrv.success('新增成功');
        }
        this.goBack();
      }
    });
  }

  /*
   * 根据地区code查询地区列表
   */
  getRegionDetailByCode(regionCode: any) {
    return this.service.request(this.service.$api_get_region_by_code, { regionCode });
  }

  // 识别身份证 参数isFront：front-正面、back-背面；type：0-申请人身份证，1-法定代表人身份证
  checkIdCard(imgurl: any, isFront: string, type: number) {
    const params = {
      idCardUrl: imgurl,
      side: isFront
    };
    this.service.request(this.service.$api_ocr_recognize_id_card, params).subscribe(res => {
      if (res) {
        if (type === 1) {
          // 法定代表人证件照
          if (isFront === 'front') {
            // 正面
            if (res.name) {
              this.sf1.setValue('/legalPersonIdentityVO/name', res.name);
            }
            if (res.number) {
              this.sf1.setValue('/legalPersonIdentityVO/certificateType', 0);
              this.sf1.setValue('/legalPersonIdentityVO/certificateNumber', res.number);
            }
          }
        }
        // 企业管理员证件照
        if (type === 0) {
          if (isFront === 'front') {
            // 正面
            if (res.name) {
              this.sf.setValue('/name', res.name);
            }
            if (res.number) {
              this.sf.setValue('/certificateNumber', res.number);
            }
          }
        }
      }
    });
  }

  // 识别营业执照
  checkBusinessLicense(imgurl: any) {
    console.log('触发了识别');

    this.service.request(this.service.$api_ocr_recognize_business_license, { businessLicenseUrl: imgurl }).subscribe(res => {
      if (res) {
        if (res.registrationNumber) {
          this.sf1.setValue('/unifiedSocialCreditCode', res.registrationNumber);
        }
        if (res.name) {
          this.sf1.setValue('/enterpriseName', res.name);
        }
        if (res.addressRegionCodes) {
          this.sf1.setValue('/enterpriseAddressCode', res.addressRegionCodes);
        }
        if (res.address) {
          this.sf1.setValue('/enterpriseAddress', res.address);
        }
        if (res.registeredCapital) {
          this.sf1.setValue('/registrationCapital', res.registeredCapital);
        }
        if (res.foundDate) {
          this.sf1.setValue('/enterpriseRegistrationTime', res.foundDate);
        }
        if (res.businessTermStartDate) {
          this.sf1.setValue('/operatingStartTime', res.businessTermStartDate);
        }
        if (res.businessTermEndDate) {
          this.sf1.setValue('/operatingEndTime', res.businessTermEndDate);
        } else {
          this.sf1.setValue('/isLoingDate', true);
        }
        if (res.businessScope) {
          this.sf1.setValue('/businessScope', res.businessScope);
        }
      }
    });
  }

  goBack() {
    window.history.go(-1);
  }

  private initBasicInfoSF(): SFSchema {
    return {
      properties: {
        title1: { title: '', type: 'string', ui: { widget: 'custom' } },
        tips: { title: '', type: 'string', ui: { widget: 'custom', offsetControl: 6 } },
        licensePhoto: { title: '', type: 'string', ui: { hidden: true } },
        tipsS: { title: '', type: 'string', ui: { widget: 'custom', offsetControl: 6 } },
        licensePhotoWatermark: {
          type: 'string',
          title: '营业执照',
          ui: {
            ...IMAGECONFIG,
            descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过5M',
            change: args => {
              if (args.type === 'success') {
                this.sf1.setValue('/licensePhoto', args.fileList[0].response.data.fullFilePath);
                this.checkBusinessLicense(args.fileList[0].response.data.fullFilePath);
              }
            }
          } as SFUploadWidgetSchema
        },

        enterpriseName: {
          title: '公司名称',
          type: 'string',
          minLength: 1,
          maxLength: 100,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入公司名称',
            errors: {
              required: '请输入公司名称'
            }
          }
        },
        unifiedSocialCreditCode: {
          title: '统一社会信用代码',
          type: 'string',
          minLength: 1,
          maxLength: 30,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            optionalHelp:
              '为了企业用户的使用体验，若公司代码即统一社会信用代码已在本应用其他关联平台注册，则此处填写的公司资料将同步更新至对应已注册的平台',
            placeholder: '请输入营业执照上的统一社会信用代码',
            errors: {
              required: '请输入18位公司代码'
            }
          }
        },
        industry: {
          type: 'string',
          title: '行业',
          enum: [
            { label: '普通货物道路运输', value: 5431},
          ],
          default: 0,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            widget: 'select'
          }
        },
        enterpriseAddressCode: {
          type: 'number',
          title: '营业执照所在地',
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            widget: 'cascader',
            valueProperty: 'regionCode',
            labelProperty: 'name',
            asyncData: (node: any, index: any) => {
              return new Promise(resolve => {
                this.getRegionDetailByCode(node?.regionCode || '').subscribe(
                  res => {
                    node.children = res.map((item: any) => ({ ...item, isLeaf: index === 1 }));
                  },
                  _ => {},
                  () => {
                    resolve();
                  }
                );
              });
            }
          } as SFCascaderWidgetSchema
        },
        enterpriseAddress: {
          title: '营业执照详细地址',
          type: 'string',
          minLength: 1,
          maxLength: 240,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            widget: 'textarea',
            autosize: { minRows: 2, maxRows: 5 },
            placeholder: '请输入营业执照上的完整详细地址',
            errors: {
              required: '请输入营业执照上的完整详细地址'
            }
          } as SFTextareaWidgetSchema
        },
        registrationCapital: {
          title: '注册资本',
          type: 'number',
          minimum: 1,
          maximum: 99999999999999999999,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 22, md: 22 },
            placeholder: '请输入营业执照上的注册资本',
            errors: {
              required: '请输入营业执照上的注册资本'
            },
            precision: 0
          }
        },
        staffNumber: {
          title: '从业人数',
          type: 'number',
          minimum: 1,
          maximum: 99999999999999999999,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 22, md: 22 },
            placeholder: '请输入从业人数',
            errors: {
              required: '请输入从业人数'
            },
            precision: 0
          }
        },
        enterpriseRegistrationTime: {
          title: '成立日期',
          type: 'string',
          ui: {
            ...DATECONFIG,
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            errors: {
              required: '请选择开始日期'
            }
          } as SFDateWidgetSchema
        },

        operatingStartTime: {
          title: '营业期限',
          type: 'string',
          ui: {
            ...DATECONFIG,
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            errors: {
              required: '请选择开始日期'
            }
          } as SFDateWidgetSchema
        },
        operatingEndTime: {
          title: '',
          type: 'string',
          ui: {
            ...DATECONFIG,
            grid: { xxl: 13, xl: 18, lg: 20, md: 18 },
            errors: {
              required: '请选择截止日期'
            },
            change: i => {
              this.sf1?.setValue('/isLoingDate', false);
              setTimeout(() => {
                console.log(this.sf1.value);
              }, 1000);
            }
          } as SFDateWidgetSchema
        },
        isLoingDate: {
          title: '长期',
          type: 'boolean',
          ui: {
            class: 'input-back',
            widget: 'checkbox',
            change: i => this.sf1?.setValue('/operatingEndTime', null)
          } as SFCheckboxWidgetSchema
        },
        businessScope: {
          title: '经营范围',
          type: 'string',
          minLength: 1,
          maxLength: 500,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            widget: 'textarea',
            autosize: { minRows: 3, maxRows: 5 },
            placeholder: '请输入营业执照上的营经营范围',
            errors: {
              required: '请输入营业执照上的营经营范围'
            }
          } as SFTextareaWidgetSchema
        },
        taxAuthority: {
          title: '税务机关',
          type: 'string',
          minLength: 1,
          maxLength: 30,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入营业执照上的税务机关',
            errors: {
              required: '请输入营业执照上的税务机关'
            }
          }
        },
        taxStatus: {
          title: '纳税状态',
          type: 'string',
          minLength: 1,
          maxLength: 30,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入纳税状态',
            errors: {
              required: '请输入纳税状态'
            }
          }
        },

        legalPersonIdentityVO: {
          type: 'object',
          properties: {
            title2: { title: '', type: 'string', ui: { widget: 'custom' } },
            tipsC: { title: '法定代表人证件照', type: 'string', ui: { widget: 'custom' } },
            tipsA: { title: '', type: 'string', ui: { widget: 'custom', offsetControl: 6 } },
            certificatePhotoFrontWatermark: {
              type: 'string',
              title: '',
              ui: {
                ...IMAGECONFIG,
                descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过5M',
                change: args => {
                  if (args.type === 'success') {
                    this.sf1.setValue('/legalPersonIdentityVO/certificatePhotoFront', args.fileList[0].response.data.fullFilePath);
                    this.checkIdCard(args.fileList[0].response.data.fullFilePath, 'front', 1);
                  }
                }
              } as SFUploadWidgetSchema
            },
            tipsB: { title: '', type: 'string', ui: { widget: 'custom', offsetControl: 6 } },
            certificatePhotoFront: { title: '', type: 'string', ui: { hidden: true } },
            certificatePhotoBack: { title: '', type: 'string', ui: { hidden: true } },
            certificatePhotoBackWatermark: {
              type: 'string',
              title: '',
              ui: {
                ...IMAGECONFIG,
                descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过5M',
                change: args => {
                  if (args.type === 'success') {
                    this.sf1.setValue('/legalPersonIdentityVO/certificatePhotoBack', args.fileList[0].response.data.fullFilePath);
                    this.checkIdCard(args.fileList[0].response.data.fullFilePath, 'back', 1);
                  }
                }
              } as SFUploadWidgetSchema
            },
            name: {
              title: '法人姓名',
              type: 'string',
              maxLength: 8,
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                placeholder: '请输入法人姓名'
              }
            },
            certificateType: {
              type: 'string',
              title: '法人证件类型',
              enum: [
                { label: '大陆身份证', value: 0 },
                { label: '港澳居民通行证', value: 1 },
                { label: '香港居民通行证', value: 2 }
              ],
              default: 0,
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                widget: 'select'
              }
            },
            certificateNumber: {
              title: ' 法定代表人证件号',
              type: 'string',
              format: 'id-card',
              minLength: 1,
              maxLength: 18,
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                placeholder: '请输入法定代表人证件号'
              }
            },
            title3: { title: '', type: 'string', ui: { widget: 'custom', offsetControl: 6 } },
            roadTransportPhoto: { title: '', type: 'string', ui: { hidden: true } },
            tipsY: { title: '', type: 'string', ui: { widget: 'custom', offsetControl: 6 } },
            roadTransportPhotoWatermark: {
              type: 'string',
              title: '道运证照片',
              ui: {
                ...IMAGECONFIG,
                change: args => {
                  if (args.type === 'success') {
                    console.log(args);

                    this.sf1.setValue('/legalPersonIdentityVO/roadTransportPhoto', args.fileList[0].response.data.fullFilePath);
                    this.checkTransCard(args.fileList[0].response.data.fullFilePath);
                  }
                }
              } as SFUploadWidgetSchema
            },
            roadTransportLicenceNo: {
              title: '经营许可证号',
              type: 'string',
              maxLength: 30,
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                placeholder: '请输入'
              }
            },
             roadTransportAddress: {
              title: '地址',
              type: 'string',
              maxLength: 30,
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                placeholder: '请输入'
              }
            },
            roadTransportStartTime: {
              title: '发证日期',
              type: 'string',
              format: 'date',
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                placeholder: '请输入'
              }
            },
            roadTransportEndTime: {
              title: '有效期至',
              type: 'string',
              format: 'date',
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                placeholder: '请输入'
              }
            }
          },
          required: [
            'certificatePhotoFront',
            'certificatePhotoBack',
            'name',
            'certificateType',
            'certificateNumber',
            'certificatePhotoFrontWatermark',
            'certificatePhotoBackWatermark',
            'roadTransportEndTime',
            'roadTransportStartTime',
            'roadTransportLicenceNo',
            'roadTransportPhotoWatermark',
            'roadTransportAddress',
          ]
        }
      },
      required: [
        'licensePhotoWatermark',
        'unifiedSocialCreditCode',
        'enterpriseName',
        'enterpriseAddressCode',
        'industry',
        'enterpriseAddress',
        'registrationCapital',
        'enterpriseRegistrationTime',
        'operatingStartTime',
        'businessScope',
        'taxStatus',
        'staffNumber',
        'taxAuthority'
      ]
    };
  }

  private initOthersSF(): SFSchema {
    return {
      properties: {
        title99: { title: '', type: 'string', ui: { widget: 'custom' } },
        website: {
          title: '平台网址',
          type: 'string',
          maxLength: 70,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入平台网址'
          }
        },
        costRate: {
          title: '成本费率',
          type: 'string',
          addOnAfter: '%',
          ui: {
            addOnAfter: '%',
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入成本费率'
          }
        }
      },
      required: ['website', 'costRate']
    };
  }
  // 道路运输证识别
  checkTransCard(imgurl: any) {
    const params = {
      transportationLicenseUrl: imgurl
    };
    this.service.request(this.service.$api_recognizeTransportationLicense, params).subscribe(res => {
      if (res) {
        this.sf.setValue('/roadTransportLicenceNo', res?.businessCertificate);
        this.sf.setValue('/roadTransportStartTime', res?.issueDate);
      }
    });
  }
}
